// Material Request sync to WDT - follow Sales Order implementation

// 直接设置listview_settings
frappe.listview_settings["Material Request"] = frappe.listview_settings["Material Request"] || {};

// 添加onload函数
frappe.listview_settings["Material Request"].onload = function(listview) {
    // Add "Sync to WDT" menu item
    listview.page.add_menu_item(__("Sync to WDT"), function() {
        sync_material_requests_to_wdt(listview);
    });

    // Add "Cancel in WDT" menu item
    listview.page.add_menu_item(__("Cancel in WDT"), function() {
        cancel_material_requests_in_wdt(listview);
    });
};

// 添加行操作按钮
frappe.listview_settings["Material Request"].button = {
    show: function(doc) {
        // 只对已提交的物料申请单显示同步按钮
        return doc.docstatus === 1 && doc.status !== "Completed";
    },
    get_label: function() {
        return __("Sync to WDT");
    },
    get_description: function(doc) {
        return __("Sync Material Request to WDT");
    },
    action: function(doc) {
        sync_single_material_request_to_wdt(doc);
    }
};

// 添加取消按钮（行操作）
frappe.listview_settings["Material Request"].button_wdt_cancel = {
    show: function(doc) {
        return doc.docstatus === 1 && doc.status !== "Completed" && doc.status !== "Cancelled";
    },
    get_label: function() {
        return __("Cancel Request");
    },
    get_description: function(doc) {
        return __("Cancel Material Request in WDT");
    },
    action: function(doc) {
        cancel_single_material_request_in_wdt(doc);
    }
};

// 同步单个物料申请单到旺店通
function sync_single_material_request_to_wdt(doc) {
    // 调试信息
    console.log("sync_single_material_request_to_wdt called with doc:", doc);
    
    // 检查doc和name是否存在
    if (!doc) {
        frappe.msgprint(__("Error: Material Request not found"));
        return;
    }
    
    // 获取物料申请单名称
    let materialRequestName = doc.name;
    
    if (!materialRequestName) {
        frappe.msgprint(__("Error: Material Request name missing"));
        console.log("Available doc fields:", Object.keys(doc));
        return;
    }
    
    // 检查物料申请单状态
    if (doc.docstatus !== 1) {
        frappe.msgprint(__("Only submitted Material Requests can be synced to WDT"));
        return;
    }
    
    if (doc.status === "Completed") {
        frappe.msgprint(__("Completed Material Requests cannot be synced to WDT"));
        return;
    }
    
    frappe.confirm(
        __("Sync Material Request '{0}' to WDT?", [materialRequestName]),
        function() {
            frappe.call({
                method: "upsystem.upsystem.api.sync_material_request_to_wdt",
                args: {
                    material_request_name: materialRequestName
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        frappe.show_alert({
                            message: __("Material Request synced to WDT"),
                            indicator: "green"
                        });
                    } else {
                        let errorMsg = r.message.message || "Unknown error";
                        frappe.msgprint({
                            title: __("Sync Failed"),
                            message: __("Material Request sync failed: {0}", [errorMsg]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("Sync failed: {0}", [err.message || "Network error"]),
                        indicator: "red"
                    });
                }
            });
        }
    );
}

// 批量同步物料申请单到旺店通
function sync_material_requests_to_wdt(listview) {
    // 调试信息
    console.log("sync_material_requests_to_wdt called with listview:", listview);
    
    // 获取选中的物料申请单
    let selected_requests = [];
    
    // 方法1：尝试使用get_checked_items()
    if (typeof listview.get_checked_items === 'function') {
        selected_requests = listview.get_checked_items();
        console.log("get_checked_items()返回:", selected_requests);
    }
    
    // 方法2：如果上面方法返回的不是数组或为空，尝试其他方法
    if (!Array.isArray(selected_requests) || selected_requests.length === 0) {
        console.log("尝试其他方法获取选中物料申请单");
        
        // 从DOM获取选中的行
        let checked_rows = listview.wrapper.find('input[type="checkbox"]:checked');
        console.log("找到选中的复选框数量:", checked_rows.length);
        
        checked_rows.each(function() {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            
            // 获取物料申请单名称 - 尝试多种方式
            let material_request_name = row.find('[data-fieldname="name"]').text().trim() ||
                                     row.find('.list-row-col[data-fieldname="name"]').text().trim() ||
                                     row.attr('data-name') ||
                                     row.find('a[data-name]').attr('data-name') ||
                                     row.find('.list-row-col:first').text().trim();
            
            if (material_request_name && material_request_name.length > 1) { // 确保不是单个字符
                selected_requests.push({name: material_request_name});
                console.log("找到物料申请单名称:", material_request_name);
            }
        });
    }
    
    console.log("最终选中的物料申请单:", selected_requests);
    
    if (selected_requests.length === 0) {
        frappe.msgprint(__("Please select Material Requests to sync"));
        return;
    }

    frappe.confirm(
        __("Sync selected {0} Material Requests to WDT?", [selected_requests.length]),
        function() {
            // 确保获取正确的物料申请单名称
            let material_request_names = selected_requests.map(request => {
                let name = request.name || request;
                console.log("处理物料申请单:", request, "-> 名称:", name);
                return name;
            }).filter(name => name && name.length > 1); // 过滤掉无效的名称
            
            console.log("准备同步的物料申请单名称:", material_request_names);
            
            frappe.call({
                method: "upsystem.upsystem.api.batch_sync_material_requests_to_wdt",
                args: {
                    material_request_names: material_request_names
                },
                callback: function(r) {
                    if (r.message && r.message.success) {
                        let success_count = r.message.data.success_count || 0;
                        let fail_count = r.message.data.fail_count || 0;
                        let results = r.message.data.results || [];
                        
                        if (fail_count === 0) {
                            frappe.show_alert({
                                message: __("All Material Requests synced. Total {0}", [success_count]),
                                indicator: "green"
                            });
                        } else {
                            // show detail failures
                            let fail_requests = results.filter(r => !r.success).map(r => r.material_request_name).join(', ');
                            frappe.msgprint({
                                title: __("Sync Finished"),
                                message: __("Success: {0}, Failed: {1}<br/>Failed Requests: {2}", 
                                    [success_count, fail_count, fail_requests]),
                                indicator: "orange"
                            });
                        }
                        
                        // 刷新列表
                        listview.refresh();
                    } else {
                        frappe.msgprint({
                            title: __("Sync Failed"),
                            message: __("Batch sync failed: {0}", [r.message.message || "Unknown error"]),
                            indicator: "red"
                        });
                    }
                },
                error: function(err) {
                    frappe.show_alert({
                        message: __("Batch sync failed: {0}", [err.message || "Network error"]),
                        indicator: "red"
                    });
                }
            });
        }
    );
}

// 取消单个物料申请单在旺店通中的对应入库单
function cancel_single_material_request_in_wdt(doc) {
    console.log("cancel_single_material_request_in_wdt called with doc:", doc);

    if (!doc) {
        frappe.msgprint(__("错误：未找到物料申请单信息"));
        return;
    }

    let materialRequestName = doc.name;
    if (!materialRequestName) {
        frappe.msgprint(__("错误：物料申请单名称不存在"));
        return;
    }

    if (doc.docstatus !== 1) {
        frappe.msgprint(__("只有已提交的物料申请单才能取消"));
        return;
    }
    if (doc.status === "Completed") {
        frappe.msgprint(__("已完成的物料申请单不能取消"));
        return;
    }
    if (doc.status === "Cancelled") {
        frappe.msgprint(__("已取消的物料申请单不能重复取消"));
        return;
    }

    let d = new frappe.ui.Dialog({
        title: __("取消物料申请单"),
        fields: [
            {
                fieldtype: "Data",
                fieldname: "cancel_reason",
                label: __("取消原因"),
                reqd: 1,
                placeholder: "请输入取消原因...",
            },
        ],
        primary_action_label: __("确认取消"),
        primary_action(values) {
            d.hide();

            let currentUser = frappe.user.name;
            let currentDateTime = frappe.datetime.now_datetime();
            let fullCancelReason = `${values.cancel_reason} | 取消人: ${currentUser} | 取消时间: ${currentDateTime}`;

            frappe.call({
                method: "upsystem.upsystem.api.cancel_material_request_in_wdt",
                args: {
                    material_request_name: materialRequestName,
                    cancel_reason: fullCancelReason,
                },
                callback(r) {
                    show_cancel_result_dialog_mr(materialRequestName, values.cancel_reason, r.message);
                },
                error(err) {
                    frappe.show_alert({
                        message: __("取消失败: {0}", [err.message || "网络错误"]),
                        indicator: "red",
                    });
                },
            });
        },
    });

    d.show();
}

// 显示取消结果
function show_cancel_result_dialog_mr(materialRequestName, cancelReason, result) {
    let message = "";

    if (result && result.success) {
        message = __("物料申请单取消成功！");
    } else {
        message = __("物料申请单取消失败: {0}", [result?.message || "未知错误"]);
    }

    const d = new frappe.ui.Dialog({
        title: __("取消结果 - {0}", [materialRequestName]),
        fields: [
            {
                fieldtype: "Small Text",
                fieldname: "result_message",
                label: __("结果信息"),
                default: message,
                read_only: 1,
            },
            {
                fieldtype: "Small Text",
                fieldname: "result_json",
                label: __("详细返回结果"),
                default: JSON.stringify(result || {}, null, 2),
                read_only: 1,
            },
        ],
        size: "large",
    });

    d.show();
}

// 批量取消物料申请单
function cancel_material_requests_in_wdt(listview) {
    console.log("cancel_material_requests_in_wdt called with listview:", listview);

    let selected_requests = [];
    if (typeof listview.get_checked_items === "function") {
        selected_requests = listview.get_checked_items();
    }

    if (!Array.isArray(selected_requests) || selected_requests.length === 0) {
        let checked_rows = listview.wrapper ? listview.wrapper.find('input[type="checkbox"]:checked') : $('input[type="checkbox"]:checked');
        checked_rows.each(function () {
            let checkbox = $(this);
            let row = checkbox.closest('tr, .list-row');
            let name = row.find('[data-fieldname="name"]').text().trim() ||
                       row.find('.list-row-col[data-fieldname="name"]').text().trim() ||
                       row.attr('data-name') ||
                       row.find('a[data-name]').attr('data-name') ||
                       row.find('.list-row-col:first').text().trim();
            if (name && name.length > 1) {
                selected_requests.push({ name });
            }
        });
    }

    if (selected_requests.length === 0) {
        frappe.msgprint(__("请先选择要取消的物料申请单"));
        return;
    }

    if (selected_requests.length > 5) {
        frappe.confirm(
            __("您选择了 {0} 个物料申请单，确定要取消吗？", [selected_requests.length]),
            function () {
                cancel_multiple_material_requests_in_wdt(selected_requests);
            }
        );
    } else {
        cancel_multiple_material_requests_in_wdt(selected_requests);
    }
}

// 取消多个物料申请单
function cancel_multiple_material_requests_in_wdt(selected_requests) {
    let names = selected_requests
        .map((r) => r.name || r)
        .filter((n) => n && n.length > 1);

    let d = new frappe.ui.Dialog({
        title: __("批量取消物料申请单"),
        fields: [
            {
                fieldtype: "Data",
                fieldname: "cancel_reason",
                label: __("取消原因"),
                reqd: 1,
                placeholder: "请输入批量取消原因...",
            },
        ],
        primary_action_label: __("确认批量取消"),
        primary_action(values) {
            d.hide();

            let currentUser = frappe.user.name;
            let currentDateTime = frappe.datetime.now_datetime();
            let fullCancelReason = `${values.cancel_reason} | 取消人: ${currentUser} | 取消时间: ${currentDateTime}`;

            frappe.show_alert({
                message: __("正在取消 {0} 个物料申请单...", [names.length]),
                indicator: "blue",
            });

            let all_cancel_data = [];
            let completed_count = 0;

            names.forEach(function (name) {
                frappe.call({
                    method: "upsystem.upsystem.api.cancel_material_request_in_wdt",
                    args: {
                        material_request_name: name,
                        cancel_reason: fullCancelReason,
                    },
                    callback(r) {
                        completed_count++;
                        if (r.message && r.message.success) {
                            all_cancel_data.push({ material_request: name, success: true, data: r.message.data });
                        } else {
                            let errorMsg = (r.message && r.message.message) || "取消失败";
                            let wdtCode = r.message?.wdt_code || "";
                            let wdtFlag = r.message?.wdt_flag || "";
                            let wdtMessage = r.message?.wdt_message || "";
                            let detailedError = errorMsg;
                            if (wdtCode || wdtFlag || wdtMessage) {
                                detailedError += ` (旺店通: ${wdtCode || wdtFlag || wdtMessage})`;
                            }
                            all_cancel_data.push({ material_request: name, success: false, error: detailedError, wdt_code: wdtCode, wdt_flag: wdtFlag, wdt_message: wdtMessage });
                        }
                        if (completed_count === names.length) {
                            show_batch_cancel_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_cancel_data.filter((x) => x.success).length,
                                    fail_count: all_cancel_data.filter((x) => !x.success).length,
                                    results: all_cancel_data,
                                },
                            });
                        }
                    },
                    error(err) {
                        completed_count++;
                        all_cancel_data.push({ material_request: name, success: false, error: err.message || "网络错误" });
                        if (completed_count === names.length) {
                            show_batch_cancel_result_dialog({
                                success: true,
                                data: {
                                    success_count: all_cancel_data.filter((x) => x.success).length,
                                    fail_count: all_cancel_data.filter((x) => !x.success).length,
                                    results: all_cancel_data,
                                },
                            });
                        }
                    },
                });
            });
        },
    });

    d.show();
}
